package com.indexServer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URLDecoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http2.HttpUtil;
import io.netty.util.CharsetUtil;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;

//z设置处理逻辑处理请求
public class HttpServerHanderByNetty extends SimpleChannelInboundHandler<FullHttpRequest> 

{
	private String url;
	private FullHttpRequest request;
	public HttpServerHanderByNetty(String url)
	{this.url=url;}
	
	
	@Override
	protected void messageReceived(ChannelHandlerContext cc, FullHttpRequest fr) throws Exception 
	{
        if (!fr.decoderResult().isSuccess()) {
        	//如果解码失败直接构造400错误返回
            sendError(cc, HttpResponseStatus.BAD_REQUEST);
            return;
        }
        
        final String url=fr.uri();
        final String path=fr.uri();
        
		if(fr.method()== HttpMethod.GET)//判断是否为get方法，只有get方法才执行如下逻辑
		{
		//设置响应
			
			System.out.println("请求的url是===："+fr.uri());
			   //创建成功的http响应消息
	        FullHttpResponse response=new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
	        //设置消息头的类型是html文件，不要设置为text/plain，客户端会当做文本解析
	        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8");
			//返回消息给浏览器
			//判断请求内容是否符合，是则返回目标网址
	        	
				StringBuilder sb=getFiles(fr.uri());
			
			   ByteBuf buffer=Unpooled.copiedBuffer(sb,CharsetUtil.UTF_8);
		        //将缓冲区的内容写入响应对象，并释放缓冲区
		        response.content().writeBytes(buffer);
		        buffer.release();
		        //将响应消息发送到缓冲区并刷新到SocketChannel中
		        cc.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
			
		}else
		{
			sendError(cc,HttpResponseStatus.METHOD_NOT_ALLOWED);
            return;
		}
		
		
		
		
	}
	  private StringBuilder getFiles(String url ) throws Exception 
	  {
		  String filePath=this.url+url;
			System.out.println("all-url是===："+filePath);

		  StringBuilder buf=new StringBuilder();
		  FileInputStream fis = new FileInputStream(filePath);
		  byte[] buffer = new byte[10];
		  while (fis.read(buffer) != -1) {
			    buf.append(new String(buffer));
			    buffer = new byte[10];
			}
			fis.close();
		  
		  return buf;
	  }
	
    private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }




}
